//
//  KSNavi.m
//  BasketBallLeagues
//
//  Created by kenshin on 4/28/17.
//  Copyright © 2017 kenshin. All rights reserved.
//

#import "KSNavi.h"

@implementation KSNavi

- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}


+ (void)push:(UIViewController*)vc {
    [self push:nil vc:vc];
}

+ (void)push:(UINavigationController*)navi vc:(UIViewController*)vc
{
    [self push:navi vc:vc animated:YES];
}

+ (void)push:(UINavigationController*)navi vc:(UIViewController*)vc animated:(BOOL)animated
{
    if(!navi)
    {
        navi = [self defaultNavi];
    }
    [navi pushViewController:vc animated:animated];
}

+ (void)popToRoot:(BOOL)animated
{
    [[self defaultNavi] popToRootViewControllerAnimated:animated];
}

+ (void)pop {
    [[self defaultNavi] popViewControllerAnimated:YES];
}
+ (UINavigationController *)defaultNavi
{
    UIViewController *topViewController = [self topViewController];
    UINavigationController *navigationController = nil;
    if ([topViewController isKindOfClass:[UINavigationController class]])
    {
        navigationController = (UINavigationController *)topViewController;
    } else if ([topViewController isKindOfClass:[UITabBarController class]]){
        navigationController = [(UITabBarController *)topViewController selectedViewController].navigationController;
        if (!navigationController) {
            navigationController = [(UITabBarController *)topViewController selectedViewController];
        }
    } else {
        navigationController = topViewController.navigationController;
    }
    return navigationController;
}

+ (UIViewController *)topViewController
{
    return [self topViewController:[[UIApplication sharedApplication].delegate window].rootViewController];
}

+ (UIViewController *)topViewController:(UIViewController *)rootViewController
{
    if (!rootViewController.presentedViewController)
    {
        return rootViewController;
    }
    
    if ([rootViewController.presentedViewController isKindOfClass:[UINavigationController class]])
    {
        UINavigationController *navigationController = (UINavigationController *)rootViewController.presentedViewController;
        UIViewController *lastViewController = [[navigationController viewControllers] lastObject];
        return [self topViewController:lastViewController];
    }
    UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController;
    return [self topViewController:presentedViewController];
}


@end
